package com.big_data_studio.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.big_data_studio.entity.Role;
import com.big_data_studio.entity.UserRole;
import com.big_data_studio.mapper.UserRoleMapper;
import com.big_data_studio.service.IRoleService;
import com.big_data_studio.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Autowired
    IUserRoleService userRoleService;
    @Autowired
    IRoleService roleService;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Value("${register.roleId}")
    private int initialRoleId;

    @Override
    public List<UserRole> getRoleIdsByUserId(int userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return userRoleService.list(wrapper);
    }

    @Override
    public void saveRoleChanges(int uid, List<Role> roles) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", uid);
        userRoleMapper.delete(wrapper);
        roles.forEach(r -> {
            UserRole ur = new UserRole();
            ur.setUserId(uid);
            ur.setRoleId(r.getId());
            userRoleService.save(ur);
        });
    }

    @Override
    public void registerUserRole(int uid) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", uid);
        UserRole ur = new UserRole();
        ur.setUserId(uid);
        ur.setRoleId(initialRoleId);
        userRoleService.save(ur);
    }
}
